"""
数据库连接和查询封装
"""
import sqlite3
import mysql.connector
from typing import Dict, List, Any, Optional
from config.settings import settings
import logging

logger = logging.getLogger(__name__)


class DatabaseConnector:
    """数据库连接器"""
    
    def __init__(self, db_url: str = None):
        self.db_url = db_url or settings.get("database.url", "sqlite:///app.db")
        self.connection = None
        self._parse_db_url()
    
    def _parse_db_url(self):
        """解析数据库URL"""
        if self.db_url.startswith("sqlite:///"):
            self.db_type = "sqlite"
            self.db_path = self.db_url.replace("sqlite:///", "")
        elif self.db_url.startswith("mysql://"):
            self.db_type = "mysql"
            # 解析MySQL连接参数
            url_parts = self.db_url.replace("mysql://", "").split("@")
            if len(url_parts) == 2:
                auth_part, host_part = url_parts
                username, password = auth_part.split(":")
                host_port, database = host_part.split("/")
                if ":" in host_port:
                    host, port = host_port.split(":")
                else:
                    host, port = host_port, "3306"
                
                self.db_config = {
                    "host": host,
                    "port": int(port),
                    "user": username,
                    "password": password,
                    "database": database
                }
        else:
            raise ValueError(f"不支持的数据库类型: {self.db_url}")
    
    def connect(self):
        """建立数据库连接"""
        try:
            if self.db_type == "sqlite":
                self.connection = sqlite3.connect(self.db_path)
                self.connection.row_factory = sqlite3.Row
            elif self.db_type == "mysql":
                self.connection = mysql.connector.connect(**self.db_config)
            
            logger.info(f"成功连接到 {self.db_type} 数据库")
            
        except Exception as e:
            logger.error(f"数据库连接失败: {e}")
            raise
    
    def disconnect(self):
        """断开数据库连接"""
        if self.connection:
            self.connection.close()
            self.connection = None
            logger.info("数据库连接已关闭")
    
    def execute_query(self, query: str, params: Optional[tuple] = None) -> List[Dict[str, Any]]:
        """执行查询并返回结果"""
        if not self.connection:
            self.connect()
        
        try:
            cursor = self.connection.cursor()
            cursor.execute(query, params or ())
            
            if cursor.description:
                columns = [col[0] for col in cursor.description]
                results = [dict(zip(columns, row)) for row in cursor.fetchall()]
            else:
                results = []
            
            return results
            
        except Exception as e:
            logger.error(f"查询执行失败: {e}")
            raise
        finally:
            if cursor:
                cursor.close()
    
    def execute_update(self, query: str, params: Optional[tuple] = None) -> int:
        """执行更新操作并返回影响行数"""
        if not self.connection:
            self.connect()
        
        try:
            cursor = self.connection.cursor()
            cursor.execute(query, params or ())
            self.connection.commit()
            
            return cursor.rowcount
            
        except Exception as e:
            logger.error(f"更新操作失败: {e}")
            self.connection.rollback()
            raise
        finally:
            if cursor:
                cursor.close()
    
    def execute_many(self, query: str, params_list: List[tuple]) -> int:
        """批量执行操作"""
        if not self.connection:
            self.connect()
        
        try:
            cursor = self.connection.cursor()
            cursor.executemany(query, params_list)
            self.connection.commit()
            
            return cursor.rowcount
            
        except Exception as e:
            logger.error(f"批量操作失败: {e}")
            self.connection.rollback()
            raise
        finally:
            if cursor:
                cursor.close()
    
    def table_exists(self, table_name: str) -> bool:
        """检查表是否存在"""
        if self.db_type == "sqlite":
            query = "SELECT name FROM sqlite_master WHERE type='table' AND name=?"
        elif self.db_type == "mysql":
            query = "SHOW TABLES LIKE %s"
        
        results = self.execute_query(query, (table_name,))
        return len(results) > 0
    
    def __enter__(self):
        """上下文管理器入口"""
        self.connect()
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """上下文管理器出口"""
        self.disconnect()


# 全局数据库连接器实例
db_connector = DatabaseConnector()